<template>
  <div class="product-info-all">
    <div v-if="product != null" class="product-info">
      <div class="prodcut-img">
        <img height="400" :src="baseUrl + product.img">
      </div>
      <div class="product-buy">
        <div class="pi-desc">{{product.pdesc}}</div>
        <div class="pi-price">
          <span class="pi-title">价格：</span>
          <span>￥{{product.price}}</span>
        </div>
        <div class="pi-stock">
          <span class="pi-title">库存：</span>
          <span>{{product.stock}}</span>
        </div>
        <div class="buy-num">
          <span class="pi-title">购买数量：</span>
          <el-input-number v-model="num" :min="0" :max="product.stock" label="购买数量"></el-input-number>
        </div>
        <div class="pi-sum-price">
          <span class="pi-title">总价：</span>
          <span>{{calculationPrices()}}元</span>
        </div>
        <div class="buy-button">
          <el-button type="primary" @click="addShopCart" icon="el-icon-sold-out">加入购物车</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ProductInfo",
  data() {
    return {
      product: null,
      num: 1
    };
  },
  created() {
    this.getProduct();
  },
  watch: {
    $route: function() {
      this.getProduct();
    }
  },
  methods: {
    getProduct() {
      this.axios
        .get("/product//public/queryById?id=" + this.$route.query.id)
        .then(res => {
          this.product = res.data.data;
        });
    },
    calculationPrices() {
      return (this.product.price * 1000 * this.num) / 1000;
    },
    getShopCarts() {
      this.axios.get("/shopCart/front/getAll").then(res => {
        this.$root.$data.cart = res.data.data;
      });
    },
    addMethod() {
      this.getShopCarts();
    },
    addShopCart() {
      if (this.num <= 0) {
        this.$message({
          showClose: true,
          message: "至少需要购买一件商品",
          type: "error"
        });
        return;
      }
      let param = {
        pid: this.product.id,
        num: this.num
      };
      this.$myPost(this, "/shopCart/front/add", this.addMethod, param);
    }
  }
};
</script>

<style scoped lang="scss">
.product-info-all {
  min-height: 78vh;
}
.product-info {
  display: flex;
}

.product-buy > .pi-desc {
  font-size: 27px;
}

.product-buy {
  margin-left: 20px;
  > * {
    font-size: 20px;
    margin: 30px 0;
    > span:not(.pi-title) {
      color: red;
    }
  }
}

.pi-title {
  color: #999;
}
</style>